package com.jy.filter;

import com.jy.entity.Authority;

import java.io.IOException;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/*
 * 登陆检查过滤器
 */
//@WebFilter("/login/*")
//@WebFilter("*.jsp")
@WebFilter({"/user/*","/vip/*"})
public class Filter1_LoginFilter implements Filter {

	public void destroy() {
		System.out.println("LoginFilter 销毁");
	}
	//doFilter(1、请求,2、响应,3、过滤器链)
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req=(HttpServletRequest)request;
		HttpServletResponse res=(HttpServletResponse)response;
		String uri=req.getRequestURI();//访问路径
		System.out.println("访问路径:"+uri);
		System.out.println("LoginFilter 正在过滤....");
	/*	//充值页不拦截
		if(uri.endsWith("vip.jsp")){
			chain.doFilter(request, response);
			return;
		}
		String user=request.getParameter("user");
		if("admin".equals(user)){
			//进入下一个过滤器(放行)
			chain.doFilter(request, response);
		}else{
			res.sendRedirect("/FilterTest/vip.jsp");
		}*/
	/*	String uri=req.getRequestURI();//访问路径
		System.out.println("访问路径:"+uri);
		Object act=req.getSession().getAttribute("act");
		System.out.println(act);
		Object vip=req.getSession().getAttribute("vip");
		System.out.println(vip);
		if(act==null){
			res.sendRedirect("/FilterTest/nologin/login.jsp");
			return;
		}else if(uri.endsWith("vip1.jsp") && vip==null && act!=null){
			res.sendRedirect("/FilterTest/nologin/vip.jsp");
			return;
		}else{
			chain.doFilter(request, response);
		}
		System.out.println("HelloFilter 正在过滤....");*/
		//session存在,登录后的标志
		HttpSession session=req.getSession();
		Object logined=session.getAttribute("LOGIN");
		List auths=(List)session.getAttribute("auths");
		System.out.println("我="+auths);
		boolean ok=this.check(uri,auths);
		if(ok) {
			//有权
			chain.doFilter(request, response);
		}else{
			//无权
			res.sendRedirect("/quanxian/noauth.jsp");
		}
	}
	//检查uri路径 我能不能访问
	private boolean check(String path,List auths){
		boolean ok=false;
		for(int i=0;i<auths.size();i++){
			Authority auth=(Authority) auths.get(i);
			if(path.contains(auth.getAuthPath())){
				ok=true;
				break;
			}
		}
		return ok;
	}
	public void init(FilterConfig fConfig) throws ServletException {
			System.out.println("LoginFilter 初始化");
	}

}
